Objects and classes

Introduction to OOP

What is an object?

All values in Python are objects

Objects are instances of a data type

Objects Have Properties

Attributes — data the object stores

Methods — actions the object can perform

What is a class?

A class defines a data type

Classes are blueprints for creating objects

You’ve Used Classes Before

int, str, float, list, bool

These are all classes!

You’ve Used Methods Before

mylist.append("value")
mystring.upper()
myfile.close()

Example: The Dog Class

Let’s build a class from scratch

We’ll learn:

  • How to create (instantiate) objects

  • How to store data (attributes)

  • How to add behavior (methods)

Creating a Simple Class

class Dog:
    pass

That’s it! We’ve defined a class.

Creating Objects (Instantiation)

class Dog:
    pass
fido = Dog()
rex = Dog()

Call the class like a function to create an instance

Adding Attributes

fido = Dog()
fido.name = "Fido"
fido.age = 3
fido.breed = "Labrador"
print(fido.name)
print(fido.age)
Fido
3

Why Attributes Beat Global Variables

# Messy: global variables
fido_name = "Fido"
fido_age = 3
rex_name = "Rex"
rex_age = 5
# Clean: attributes
fido.name = "Fido"
fido.age = 3
rex.name = "Rex"
rex.age = 5

Adding Methods

class Dog:
    def bark(self):
        print("Woof!")
fido = Dog()
fido.bark()
Woof!

Understanding self

self refers to the object running the method

class Dog:
    def bark(self):
        print(f"{self.name} says Woof!")
fido = Dog()
fido.name = "Fido"
rex = Dog()
rex.name = "Rex"

fido.bark()
rex.bark()
Fido says Woof!
Rex says Woof!

The __init__() Method

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print(f"{self.name} says Woof!")
fido = Dog("Fido", 3)
print(fido.name, fido.age)
Fido 3

Building a Complete Dog

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.hunger = 5  # Scale of 0-10

    def bark(self):
        print(f"{self.name} says Woof!")

    def eat(self):
        self.hunger = max(0, self.hunger - 3)
        print(f"{self.name} ate! Hunger: {self.hunger}")

    def pass_time(self):
        self.hunger = min(10, self.hunger + 1)

Using Our Dog Class

buddy = Dog("Buddy", 2)
buddy.bark()
Buddy says Woof!
buddy.hunger
5
buddy.eat()
buddy.eat()
Buddy ate! Hunger: 2
Buddy ate! Hunger: 0
buddy.pass_time()
buddy.pass_time()
buddy.hunger
2

Example: Summary

We built a Dog class with:

  • Instantiation: Dog("Fido", 3)

  • Attributes: name, age, hunger

  • Methods: bark(), eat(), pass_time()

Defining Classes: The Rules

class ClassName:
body

Use CamelCase for class names

The pass Statement

pass does nothing—it’s a placeholder

class Blob:
    pass

Use when you need a body but have nothing to put there

Methods Need self

class Greeter:
    def greet(self):
        print(f"Hi, I'm {self.name}!")

self = the object running the method

__init__() Initializes Objects

class Greeter:
    def __init__(self, name):
        self.name = name

Called automatically when object is created

Attributes vs Parameters

def __init__(self, name, age):
    self.name = name        # Parameter → Attribute
    self.age = age          # Parameter → Attribute
    self.hunger = 5         # No parameter, default value
    # age + 1               # Could use parameter without storing it

Class Definition: Summary

  • class ClassName: to define

  • ClassName() to instantiate

  • Methods need self as first parameter

  • __init__() sets up new objects

  • Attributes are variables on self

Docstrings for Classes

Document your code for others (and future you)

Class Docstring Format

class Dog:
    """A virtual pet dog that tracks hunger.

    Attributes:
        name (str): the dog's name.
        age (int): the dog's age in years.
        hunger (int): hunger level from 0 (full) to 10 (starving).
    """

Method Docstrings

def eat(self):
    """Feed the dog, reducing hunger by 3.

    Hunger will not go below 0.
    """
    self.hunger = max(0, self.hunger - 3)

Docstrings Must Come First

# Correct - docstring first
def greet(self):
    """Say hello."""
    print("Hello!")
# Wrong - docstring not first
def greet(self):
    print("Hello!")
    """This won't work as a docstring."""

Docstrings: Summary

  • Class docstrings describe purpose and attributes

  • Method docstrings describe behavior

  • Must be the first statement in the body

  • Use help() to view docstrings

Complete Example

class Dog:
    """A virtual pet dog that tracks hunger.

    Attributes:
        name (str): the dog's name.
        age (int): the dog's age in years.
        hunger (int): hunger level from 0 (full) to 10 (starving).
    """

    def __init__(self, name, age):
        """Create a new Dog.

        Args:
            name (str): the dog's name.
            age (int): the dog's age in years.
        """
        self.name = name
        self.age = age
        self.hunger = 5

Complete Example (continued)

    def bark(self):
        """Make the dog bark."""
        print(f"{self.name} says Woof!")

    def eat(self):
        """Feed the dog, reducing hunger by 3 (minimum 0)."""
        self.hunger = max(0, self.hunger - 3)
        print(f"{self.name} ate! Hunger: {self.hunger}")

    def pass_time(self):
        """Simulate time passing. Increases hunger by 1 (maximum 10)."""
        self.hunger = min(10, self.hunger + 1)

    def status(self):
        """Print the dog's current status."""
        mood = "happy" if self.hunger < 5 else "hungry"
        print(f"{self.name} ({self.age} yrs) - Hunger: {self.hunger} - {mood}")

OOP: Key Takeaways

  • Objects combine data and functionality

  • Classes are blueprints for objects

  • Attributes store data (self.name)

  • Methods define behavior (def bark(self))

  • __init__() initializes new objects

Practice Ideas

Create your own classes:

  • BankAccount — balance, deposit(), withdraw()

  • Student — name, grades list, add_grade(), gpa()

  • Rectangle — width, height, area(), perimeter()